package casa.depesos.app.com.frag;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.base.utils.SPHelper;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.support.toast.ToastUtil;

import java.util.List;

import casa.depesos.app.com.R;
import casa.depesos.app.com.activity.LoginActivity;
import casa.depesos.app.com.databinding.FragmentLoginBinding;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.RightDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.req.IsRegReq;
import casa.depesos.app.com.http.req.no.SloganReq;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class PhoneLoginFragment extends BaseFragment {

    protected FragmentLoginBinding binding;
    protected String phone;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Report.show("ACTION_CC_001");
        new SloganReq().req();
    }

    protected void changeWay() {
        Report.click("ACTION_CC_004");
        ((LoginActivity) getActivity()).changeWay(binding.phone.getText().toString().trim());
    }

    public PhoneLoginFragment setPhone(String s) {
        phone = s;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentLoginBinding.inflate(inflater, container, false);
        binding.getRoot().setPadding(0, Utils.getStatusBarHeight(getActivity()), 0, 0);
        binding.way.setOnClickListener(v -> {
            changeWay();
        });

        binding.check.setText(getString(R.string.check0) + getString(R.string.check1));
        Utils.setClickableText(binding.check, Constant.PRIVACY, null);
        binding.phone.addTextChangedListener(new TextWatcher() {
            boolean report = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int len = s.toString().length();
                if (len > 0) {
                    binding.clear.setVisibility(View.VISIBLE);
                    if (!report) {
                        report = true;
                        reportInputPhone();
                    }
                } else {
                    binding.clear.setVisibility(View.INVISIBLE);
                }
                checkNext();
            }
        });
        Utils.setNumberEditTextInputSpace(binding.phone, 10);
        binding.clear.setOnClickListener(v -> binding.phone.setText(""));

        if (!TextUtils.isEmpty(phone)) {
            binding.phone.setText(phone);
        }
        binding.next.setOnClickListener(v -> next());
        return binding.getRoot();
    }

    protected void reportInputPhone() {
        Report.click("ACTION_CC_002");
    }

    protected boolean checkNext() {
        int len = binding.phone.getText().toString().length();
        boolean bo = len == 10;
        if (bo) {
            binding.next.setAlpha(1);
        } else {
            binding.next.setAlpha(0.6f);
        }
        return bo;
    }

    protected String checkPhone() {
        String p = binding.phone.getText().toString().trim();
        if (p.length() != 10) {
            ToastUtil.showShortToast(getActivity(), "Ingrese un número telefónico válido de 10 dígitos");
            return null;
        }
        return p;
    }

    protected void reportNextClick() {
        Report.click("ACTION_CC_003");
    }

    protected final void next() {
        String p = checkPhone();
        if (p == null) {
            return;
        }
        reportNextClick();
        showLoading();
        new IsRegReq(p).req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    if ("0".equals(bean.getCode())) {//未注册
                        jump(p, false);
                    } else {
                        jump(p, true);
                    }
                }
            }
        });
    }

    protected void jump(String p, boolean isRegistered) {
        String key = isRegistered ? "agree1" : "agree1";
        if (Constant.white || SPHelper.getInstance(getActivity()).getBoolean(key, false)) {
            jump(true, p, isRegistered);
        } else {
            Report.show("ACTION_VV_001");
            new RightDlg().setSms().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    Report.click("ACTION_VV_002");
                    if (isOk) {
                        SPHelper.getInstance(getActivity()).putBooleanAndCommit(key, true);
                    }
                    jump(isOk, p, isRegistered);
                }
            }).show(getChildFragmentManager(), "");
        }
    }

    protected void jump(boolean agree, String phone, boolean isRegistered) {
        if (agree) {
            if (!Constant.white && !Utils.hasPermission(getActivity(), Permission.READ_SMS, Permission.RECEIVE_SMS)) {
                if (isRegistered) {
                    Report.show("ACTION_DD_002");
                } else {
                    Report.show("ACTION_GG_008");
                }
                XXPermissions.with(this)
                        .permission(Permission.READ_SMS, Permission.RECEIVE_SMS)
                        .request(new OnPermissionCallback() {
                            boolean deal = false;

                            @Override
                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                                if (allGranted) {
                                    if (isRegistered) {
                                        Report.click("ACTION_DD_003");
                                    } else {
                                        Report.click("ACTION_GG_009");
                                    }
                                    toCode(true, phone, isRegistered);
                                } else {
                                    onDenied();
                                }
                            }

                            @Override
                            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                                onDenied();
                            }

                            void onDenied() {
                                if (deal) {
                                    return;
                                }
                                deal = true;
                                if (isRegistered) {
                                    Report.click("ACTION_DD_004");
                                } else {
                                    Report.click("ACTION_GG_010");
                                }
                                toCode(false, phone, isRegistered);
                            }
                        });
            } else {
                toCode(false, phone, isRegistered);
            }
        } else {
            toCode(false, phone, isRegistered);
        }
    }

    protected void toCode(boolean hasRight, String phone, boolean isRegistered) {
        if (!isRegistered) {
            ToastUtil.showLongToast(getActivity(), "Número no registrado. Regístrese antes de iniciar sesión por favor.");
        }
        ((LoginActivity) getActivity()).showCode(hasRight, phone, isRegistered);
    }
}
